package model

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

//全网上传量
const GlobalNameNetTotalUpload = "net_upload_size"

//全网路由器数量
const GlobalNameNetRouterCounts = "net_router_sales"

//全网linux节点加成数
const GlobalNameLxNodesAddNum = "lx_node_add_num"

//全网linux流量上传量加成数
const GlobalNameLxFlowAddNum = "lx_flow_add_num"

//全网7日平均收益
const GlobalNetAverageIncome = "income_ability"

//全网昨日平均收益
const GlobalNetLastAverageIncome = "last_income_ability"

//踢矿工限制条件开关：0-不限制；1-限制
const GlobalNameRemoveMinerOn = "remove_miner_on"

type GlobalVar struct {
	ID         int    `db:"id" json:"id,omitempty"`
	Value      string `db:"value" json:"value,omitempty"`
	UpdateTime int64  `db:"update_time" json:"update_time,omitempty"`
}

//查询全网总上传流量数据
//Auth: Xu
func GetTodayRouterMining(db sqlx.Queryer, name string) (res GlobalVar, err error) {
	zeroUnix := GetTodayZeroUnix()
	err = sqlx.Get(db, &res, "select value,update_time from global_var where name = ? and update_time > ?", name, zeroUnix)
	if err != nil {
		Log("info", "查询全网总上传流量数据失败！", err.Error())
	}

	return res, nil
}

//获取全局变量值
//Auth: TXG
func GetGlobalVarValue(db sqlx.Queryer, id int) (qi string, err error) {
	err = db.QueryRowx(`select value from global_var where id = ?`, id).Scan(&qi)
	return qi, err
}

//查询全网总数据
func GetGlobalVar(Name string) (res string, err error) {
	err = sqlx.Get(config.C.DB.DB, &res, "SELECT value FROM global_var WHERE name = ? limit 1", Name)
	if err == sql.ErrNoRows {
		err = errno.RecordError
		return res, err
	}
	if err != nil {
		Log("error", "查询global_var表失败 name = ", Name, err.Error())
	}
	return
}

// 更新全网数据
func UpdateGlobalVar(Name, Value string) error {
	res := sqlx.MustExec(config.C.DB.DB, "UPDATE global_var SET value = ?, update_time=unix_timestamp(now()) Where name = ?", Value, Name)
	re, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if re >= 0 {
		return nil
	}
	return err
}
